package com.cychat.mall.service.impl;

import com.Cychat.commons.entity.pojo.Product;
import com.Cychat.commons.entity.pojo.ShoppingCart;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cychat.mall.entity.DTO.CartQuantityUpdateDTO;
import com.cychat.mall.entity.DTO.ShoppingCartDTO;
import com.cychat.mall.entity.DTO.UpdateCartQuantitiesRequest;
import com.cychat.mall.mapper.ProductMapper;
import com.cychat.mall.mapper.ShoppingCartMapper;
import com.cychat.mall.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * Auther: 刘俊  <br/>
 * Date: 2025-11-2:下午 2:57  <br/>
 * Description: 购物车服务实现类
 */
@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart> implements ShoppingCartService {

    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateCartQuantities(Long userId, UpdateCartQuantitiesRequest request) {
        List<CartQuantityUpdateDTO> items = request.getItems();

        if (items == null || items.isEmpty()) {
            throw new IllegalArgumentException("更新项列表不能为空");
        }

        for (CartQuantityUpdateDTO item : items) {
            Long cartId = item.getCartId();
            Integer newQuantity = item.getQuantity();

            // 1. 校验购物车项是否存在且属于当前用户
            ShoppingCart cart = this.getById(cartId);
            if (cart == null) {
                throw new RuntimeException("购物车项不存在: cartId=" + cartId);
            }
            if (!userId.equals(cart.getUserId())) {
                throw new RuntimeException("无权限修改该购物车项: cartId=" + cartId);
            }

            // 2. 查询商品库存
            Product product = productMapper.selectById(cart.getProductId());
            if (product == null) {
                throw new RuntimeException("商品不存在: productId=" + cart.getProductId());
            }

            if (newQuantity > product.getStock()) {
                throw new RuntimeException("商品“" + product.getName() + "”库存不足，当前库存为：" + product.getStock());
            }

            // 3. 更新数量和更新时间
            cart.setQuantity(newQuantity);
            cart.setUpdateTime(new Date());
            this.updateById(cart);
        }
    }

    @Override
    public ShoppingCart getCartItem(Long userId, Integer productId) {
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, userId)
                .eq(ShoppingCart::getProductId, productId);
        return this.getOne(queryWrapper);
    }

    @Override
    public void updateCartItemQuantity(Long userId, Integer productId, int i) {
        ShoppingCart cart = getCartItem(userId, productId);
        if (cart == null) {
            throw new RuntimeException("购物车项不存在: userId=" + userId + ", productId=" + productId);
        }
        cart.setQuantity(i);
        cart.setUpdateTime(new Date());
        this.updateById(cart);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteCartItems(Long userId, List<Integer> cartIds) {
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, userId)
                .in(ShoppingCart::getCartId, cartIds);
        this.remove(queryWrapper);
    }

    @Override
    public List<ShoppingCart> listByUserIdAndCartIds(Long userId, List<Integer> cartIds) {
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, userId)
                .in(ShoppingCart::getCartId, cartIds);
        return shoppingCartMapper.selectList(queryWrapper);
    }
}
